import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/view/my_new_album_widget.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_app_bar.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyAlbumPage extends StatefulWidget {
  const MyAlbumPage({Key? key}) : super(key: key);

  @override
  _MyAlbumPageState createState() => _MyAlbumPageState();
}

class _MyAlbumPageState extends State<MyAlbumPage> with RouteAware {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 20;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
    _status = value;
    setState(() {});
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteUtils.routeObserver
        .subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    RouteUtils.routeObserver.unsubscribe(this);
    super.dispose();
  }

//回到当前页面
  @override
  void didPopNext() {
    refresh();
    print("专辑返回刷新了---");
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
  }

  //获取数据
  Future<List> loadData({int? pageNum}) async {
    return await ServiceRepository.specialAlbumList(
        page: pageNum!, pageSize: pageSize, type: 1, status: 2);
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      print("数组个数---${data.length}");
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      status = LoadStatusType.empty;
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: ++currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "专辑专区",
        actionName: "新增专辑",
        onPressed: () {
          showModalBottomSheet<void>(
              context: context,
              backgroundColor: Colors.transparent,

              /// 禁止拖动关闭
              enableDrag: false,

              /// 使用true则高度不受16分之9的最高限制
              isScrollControlled: true,
              builder: (_) {
                return SingleChildScrollView(
                    padding: EdgeInsets.only(
                        bottom: MediaQuery.of(context)
                            .viewInsets
                            .bottom), // !important
                    child: MyNewAlbumWidget(
                      onPressed: () {
                        refresh();
                      },
                    ));
              });
        },
      ),
      body: _gridViewWidget(),
    );
  }

  ///专辑
  Widget _gridViewWidget() {
    if (status != LoadStatusType.success) {
      return StatusViews(status);
    }
    return GridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      physics: BouncingScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 15,
        mainAxisSpacing: 15,
        childAspectRatio: 167 / 230,
      ),
      //maxCrossAxisExtent
      itemBuilder: (context, index) {
        return _itemWidget(list[index]);
      },
      itemCount: list.length,
    );
  }

  //item
  Widget _itemWidget(AlbumListModel model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = itemWidth * 173 / 167;
    return InkWell(
      onTap: () {},
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
                  )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10), topRight: Radius.circular(10)),
              child: LoadImage(
                model.specialAlbumThumb ?? "",
                width: double.infinity,
                fit: BoxFit.fitHeight,
                height: itemHeight,
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 7),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        model.specialAlbumTitile ?? "",
                        style: TextStyle(
                            fontFamily: Global.mySemiboldFont,
                            fontSize: 14,
                            color: Global.kTheme.textPrimary4),
                      ),
                      SizedBox(
                        height: 2,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text(
                            "版权金",
                            style: TextStyle(
                                fontSize: 12,
                                color: Global.kTheme.inputHint1,
                                fontFamily: Global.mySemiboldFont),
                          ),
                          SizedBox(
                            width: 2,
                          ),
                          Text(
                            model.specialAlbumRate ?? "",
                            style: TextStyle(
                                fontSize: 15,
                                color: Global.kTheme.textPrimary0,
                                fontFamily: Global.mySemiboldFont),
                          ),
                        ],
                      )
                    ],
                  ),
                  InkWell(
                    onTap: () {
                      showModalBottomSheet<void>(
                          context: context,
                          backgroundColor: Colors.transparent,

                          /// 禁止拖动关闭
                          enableDrag: false,

                          /// 使用true则高度不受16分之9的最高限制
                          isScrollControlled: true,
                          builder: (_) {
                            return SingleChildScrollView(
                                padding: EdgeInsets.only(
                                    bottom: MediaQuery.of(context)
                                        .viewInsets
                                        .bottom), // !important
                                child: MyNewAlbumWidget(
                                  album: model,
                                  onPressed: () {
                                    refresh();
                                  },
                                ));
                          });
                    },
                    child: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 1),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          color: Global.kTheme.colorBackground3),
                      child: Text(
                        "编辑",
                        style: TextStyle(
                            fontSize: 12,
                            color: Global.kTheme.textPrimary5,
                            fontFamily: Global.mySemiboldFont),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
